package com.bobexchen.nettywebsocket.service;

import com.bobexchen.nettywebsocket.NettyServerHandlerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

@Component
public class NettyService {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private NettyServerHandlerInitializer nettyServerHandlerInitializer;

    /**
     * 首先需要了解两个注解@Component跟@PostConstruct
     * spring注解中@component就是说把这个类交给Spring管理，因为不清楚这个类是属于哪个层面，所以就用@Component。
     *
     * @PostContruct是spring框架的注解，在方法上加该注解会在项目启动的时候执行该方法，也可以理解为在spring容器初始化的时候执行该方法。
     * @throwsException
     */
    @PostConstruct
    public void init() throws Exception {
        log.info("正在启动websocket服务器");
        //主线程组
        NioEventLoopGroup boss = new NioEventLoopGroup();

        //从线程组
        NioEventLoopGroup work = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            //指定使用的线程池
            bootstrap.group(boss, work)
                    //指定netty通道类型
                    .channel(NioServerSocketChannel.class)
                    //指定通道初始化器用来加载当Channel收到事件消息后，
                    //如何进行业务处理
                    .childHandler(new NettyServerHandlerInitializer())
                    //设置NettyServer的端口
                    .localAddress(new InetSocketAddress(9090));

            //如何进行业务处理
            bootstrap.childHandler(nettyServerHandlerInitializer);
            Channel channel = bootstrap.bind(9090).sync().channel();
            log.info("webSocket服务器启动成功：" + channel);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("运行出错：" + e);
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
            log.info("websocket服务器已关闭");
        }
    }

}
